#ifndef MQTT_CLIENT_H
#define MQTT_CLIENT_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <mosquitto.h>
#include "mqtt_config.h"

// MQTT客户端状态
typedef enum {
    MQTT_STATE_DISCONNECTED = 0,
    MQTT_STATE_CONNECTING,
    MQTT_STATE_CONNECTED,
    MQTT_STATE_RECONNECTING,
    MQTT_STATE_ERROR
} mqtt_state_t;

// MQTT消息结构
typedef struct {
    char topic[MQTT_MAX_TOPIC_SIZE];
    char payload[MQTT_MAX_MESSAGE_SIZE];
    int qos;
    int retain;
} mqtt_message_t;

// MQTT客户端结构
typedef struct {
    struct mosquitto *mosq;
    mqtt_state_t state;
    int reconnect_count;
    time_t last_heartbeat;
    pthread_mutex_t mutex;
    
    // 配置参数
    char broker_host[256];
    int broker_port;
    char client_id[128];
    char username[128];
    char password[128];
    
    // 统计信息
    unsigned long messages_sent;
    unsigned long messages_received;
    unsigned long connect_count;
} mqtt_client_t;

// 消息处理回调函数类型
typedef void (*mqtt_message_callback_t)(const char* topic, const char* payload, int payload_len);
typedef void (*mqtt_connect_callback_t)(int result);
typedef void (*mqtt_disconnect_callback_t)(int result);

// 函数声明
int mqtt_client_init(mqtt_client_t *client, const char* client_id);
int mqtt_client_connect(mqtt_client_t *client, const char* host, int port);
int mqtt_client_disconnect(mqtt_client_t *client);
int mqtt_client_cleanup(mqtt_client_t *client);

int mqtt_client_subscribe(mqtt_client_t *client, const char* topic, int qos);
int mqtt_client_unsubscribe(mqtt_client_t *client, const char* topic);
int mqtt_client_publish(mqtt_client_t *client, const char* topic, const char* payload, int qos, int retain);

int mqtt_client_set_auth(mqtt_client_t *client, const char* username, const char* password);
int mqtt_client_set_callbacks(mqtt_client_t *client, 
                             mqtt_message_callback_t msg_cb,
                             mqtt_connect_callback_t conn_cb,
                             mqtt_disconnect_callback_t disconn_cb);

void mqtt_client_loop(mqtt_client_t *client);
void mqtt_client_print_stats(mqtt_client_t *client);

// 工具函数
const char* mqtt_state_to_string(mqtt_state_t state);
void mqtt_log(int level, const char* format, ...);

#endif // MQTT_CLIENT_H